package com.yuzi.utils;

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.jfinal.kit.PropKit;
import org.apache.commons.io.FilenameUtils;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.List;

public class Doc2HtmlUtil {

    public static Process process = null;

    //直接采用服务器（/opt/openoffice4/program/soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard &）
    //目前java启动linux中的openoffice服务出现问题，还没有解决
    private static void startOpenOffice(){
        String command = PropKit.use("jConfig.properties").get("OpenOffice_START");
        InputStream is2 = null;
        BufferedReader br2 = null;
        try {
            Process p = Runtime.getRuntime().exec(command);
            final InputStream is1 = p.getInputStream();

            new Thread(new Runnable() {
                public void run() {
                    BufferedReader br = new BufferedReader(new InputStreamReader(is1));
                    try{
                        while(br.readLine() != null);
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }finally {
                        try {
                            br.close();
                            is1.close();
                        }catch (IOException ex){
                            ex.printStackTrace();
                        }
                    }
                }
            }).start(); // 启动单独的线程来清空p.getInputStream()的缓冲区

            is2 = p.getErrorStream();

            br2 = new BufferedReader(new InputStreamReader(is2));

            StringBuilder buf = new StringBuilder(); // 保存输出结果流

            String line = null;

            while((line = br2.readLine()) != null) buf.append(line); // 
                System.out.println("输出结果为：" + buf);
            int exitVal = p.waitFor();
            System.out.println("Exited with error code " + exitVal);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try{
                br2.close();
                is2.close();
            }catch (IOException ex){
                ex.printStackTrace();
            }
        }
    }

    //创建链接
    private static OpenOfficeConnection createConnect(){
        OpenOfficeConnection connection = null;
        try {
            connection = new SocketOpenOfficeConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;
    }

    //断开连接
    private static void disConnect(OpenOfficeConnection connection){
        connection.disconnect();
    }

    //销毁服务
    private static void distoryProcess(){
        process.destroy();
    }

    /**
     * @param docPath 文件路径
     * 把ppt word excel等文件生成图片文件
     * @param pdfPath  转为pdf的路径
     * @param imgPath  转为图片的路径
     */
    public static void doc2Imags(String docPath, String pdfPath,String imgPath){
        try {
            doc2Pdf(docPath, pdfPath);
            pdf2Imgs(pdfPath, imgPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //启动服务 转换为pdf

    /**
     * @param docPath   doc文件
     * @param pdfPath   转化成pdf后的文件路径
     * @throws ConnectException
     */
    public static boolean doc2Pdf(String docPath, String pdfPath) throws ConnectException {
        try {
            File inputFile = new File(docPath);
            File outputFile = new File(pdfPath);
            OpenOfficeConnection connection = createConnect();
            connection.connect();
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            //converter.convert(inputFile, outputFile);
            DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
            DocumentFormat txt = formatReg.getFormatByFileExtension("odt");

            DocumentFormat pdf = formatReg.getFormatByFileExtension("pdf");
            //DocumentFormat html = formatReg.getFormatByFileExtension("html");
            converter.convert(inputFile, txt, outputFile, pdf);
            disConnect(connection);
            return true;
        }catch (ConnectException e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将pdf转换成图片
     *
     * @param pdfPath
     * @param imgDirPath 存储图片的目录(所有图片都转为jpg格式)
     * @return 返回转换后图片的名字
     * @throws Exception
     */
    private static List<String> pdf2Imgs(String pdfPath, String imgDirPath) throws Exception {
        Document document = new Document();
        document.setFile(pdfPath);
        float scale = 2f;//放大倍数
        float rotation = 0f;//旋转角度
        List<String> imgNameList = new ArrayList<String>();
        int pageNum = document.getNumberOfPages();
        for (int i = 0; i < pageNum; i++) {
            BufferedImage rendImage = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN,
                    Page.BOUNDARY_CROPBOX, rotation, scale);
            try {
                String str = imgDirPath.substring(imgDirPath.length()-1);
                //String str1 = File.pathSeparator;     ";"
                //String str2 = File.separator;           //"/"
                if (!File.separator.equals(str)){
                    imgDirPath += File.separator;
                }
                String imgPath = imgDirPath + FilenameUtils.getName(pdfPath) + "_" + (i+1) + ".jpg";
                File file = new File(imgPath);
                ImageIO.write(rendImage, "jpg", file);
                imgNameList.add(FilenameUtils.getName(imgPath));
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            rendImage.flush();
        }
        document.dispose();
        return imgNameList;
    }

    // cd c:\Program Files (x86)\OpenOffice 4\program
    //soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
    public static void main(String[] args) {
        String docPath = args[0];
        String pdfPath = args[1];
        String imgPath = args[2];
        doc2Imags(docPath, pdfPath,imgPath);
    }
}
